#include <stdio.h>
#include <stdlib.h>
#include <mysql/mysql.h>

#define DB_SERVER   "localhost"
#define DB_NAME     "test"
#define DB_USER     "root"
#define DB_PWD      "asdf"


int query_test(char *sql);

int main(int argc, char *argv[])
{
    query_test("select * from pet limit 30;");
    exit(0);
}

int process_result_set(MYSQL *mysql, MYSQL_RES *result)
{
    MYSQL_ROW row;
    unsigned int num_fields;
    unsigned int i;

    num_fields = mysql_num_fields(result);

    while ((row = mysql_fetch_row(result)))
    {
        unsigned long *lengths;
        lengths = mysql_fetch_lengths(result);
        for(i = 0; i < num_fields; i++) {
            printf("%d[%s] ", *(int*)(lengths++), row[i] ? row[i] : "NULL");
        }
        printf("\n");
    }

    return 0;
}

int query_test(char *sql)
{
    MYSQL mysql, *db_handle;
    MYSQL_RES *result;
    int query_ret = 0;
    int status;

    fprintf(stderr, "%s\n", sql);

    mysql_init(&mysql);
    mysql_options(&mysql, MYSQL_READ_DEFAULT_GROUP, "your_prog_name");

    db_handle = mysql_real_connect(&mysql, DB_SERVER, DB_USER, DB_PWD, DB_NAME, 0, NULL, 0);
    if (db_handle == NULL) {
        fprintf(stderr, "Failed to connect to database: Error: %s\n", mysql_error(&mysql));
        mysql_close(&mysql);
        return -1;
    }

    query_ret = mysql_query(db_handle, sql);
    if (query_ret != 0) {
        fprintf(stderr, "mysql_query error: %s\n", mysql_error(db_handle));
        mysql_close(&mysql);
        return -1;
    }

    do {
        result = mysql_store_result(&mysql);
        if (result) {
            process_result_set(&mysql, result);
            mysql_free_result(result);
        } else {
            if (mysql_field_count(&mysql) == 0) {
                printf("%lld rows affected\n", mysql_affected_rows(&mysql));
            } else {
                printf("Could not retrieve result set\n");
                break;
            }
        }

        /* more results? -1 = no, >0 = error, 0 = yes (keep looping) */
        if ((status = mysql_next_result(&mysql)) > 0) {
            printf("Could not execute statement\n");
        }
    } while (status == 0);

    mysql_close(&mysql);
    return 0;
}

